var ObjectID = require("mongodb").ObjectID;
var ifm = require('../models/ifm.js');
var cfm = require('../models/cfm.js');
var collectionList = ['entity','property','impact','threat','countermeasure'];

exports.ifm = function(req, res) {
    console.log("dataIfm");
    var filter = {};
    filter["is-a."+ObjectID(req.body.cfm_id)+'._nor'] = 1;
    filter["user"]=req.body.user;
    var ifmList = {}

    var mutex = collectionList.length;//几个固定集合
    for(var i=0;i<collectionList.length;i++){
        ifmList[collectionList[i]] = {};
        console.log(collectionList[i]);
        console.log(filter)
        Ifm.get(collectionList[i],filter,function(err,doc,collectionName){
            //一次++一次--
            findChildNodes(ifmList,collectionName,doc,function(){
                mutex--;
                if(mutex===0) {
                    console.log(JSON.stringify(ifmList))
                    res.send({ifm:ifmList});
                }
            });
        });
    }

};

findChildNodes = function findChildNodes(ifmList,collectionName,doc,callback){
    var mutex = doc.length;
    if(mutex===0) return callback();

    for(var i=0;i<doc.length;i++){
        for(var key in doc[i]["is-a"]){
            //所以项目都是平行输出的，就像数据库中一样
            if(ifmList[collectionName][key]==undefined) ifmList[collectionName][key] = [doc[i]];//第一次的话直接输入
            else ifmList[collectionName][key].push(doc[i]);
        }

        var filter = {};
        //filter["is-a."+doc[i].cfm_id+'._nor'] = 1;
        filter["is-a."+doc[i]._id+'._nor'] = 1;
        //filter["user"]=doc[i].user;
        Ifm.get(collectionName,filter,function(err,doc,collectionName){
            findChildNodes(ifmList,collectionName,doc,function(){
                mutex--;
                if(mutex===0)  return callback();
            });
        });
    }
}


exports.ifmElement = function(req, res) {
    console.log("ifmElement");
    console.log(req.body)
    switch(req.body['process']){
        case 'add':
            ifmAdd(req,res);
            break;
        case 'cite':
            //ifmCite(req,res);
            break;
        case 'remove':
            ifmRemove(req,res);
            break;
        case 'revise':
            //ifmRevise(req,res);
            break;
        case 'get':
            ifmGet(req,res);
    }
};


exports.ifmRelation = function(req, res) {
    console.log("ifmRelation");
    console.log(req.body)
    switch(req.body['process']){
        case 'add':
            ifmRelationAdd(req,res);
            break;
        case 'cite':
            //ifmCite(req,res);
            break;
        case 'remove':
            ifmRelationRemove(req,res);
            break;
        case 'revise':
            ifmRelationRevise(req,res);
            break;
    }
};

ifmGet = function(req,res){
    console.log("Ifm get");
    //cite和add的方式是不一样的
    //cfm生成元素
    var collectionName = req.body.node.type.toLowerCase();
    var ifm_filter = {_id:ObjectID(req.body.node.id)}

    ifm.get(collectionName,ifm_filter,function(err,doc,collectionName){
        var ifm_doc = doc[0];
        console.log(ifm_doc)
        return res.send({ifm:ifm_doc});
    });
}

ifmAdd = function(req,res){
    console.log("Ifm add");
    //cite和add的方式是不一样的
    //cfm生成元素
    var collectionName = req.body.source.type.toLowerCase();
    if(req.body.source.id === 'null'){//新增情况，ID不存在 //错误，这个是必然不存在的
        cfm.generateItem(collectionName,function(err,doc){
            var cfm_id = doc[0]._id;
            var ifm_filter = {
                user: req.session.user.mail
                ,cfm_id: cfm_id
                ,name:{}
            };
            ifm_filter["name"][req.body.source.name] = {"_nor":1};
            ifm_filter[req.body.relation]={};
            ifm_filter[req.body.relation][req.body.target.id]={"_nor":1};


            ifm.add(collectionName,ifm_filter,function(err,doc){
                var ifm_doc = doc[0];
                if(!err){
                    var cfm_filter = [{_id:cfm_id},{}];
                    cfm_filter[1]["name"+"."+req.body.source.name+"."+"_nor"] = 1;
                    cfm_filter[1][req.body.relation+"."+cfm_id+"."+"_nor"] = 1;
                    //console.log(cfm_filter)
                    cfm.add(collectionName,cfm_filter,function(err,doc){
                    });
                }
                return res.send({ifm:ifm_doc});
            });
        });
    }else{
        //需要cfm中id的信息
    }
};

ifmRelationAdd = function(req,res){
    console.log("ifmRelation add");
    var sourceCollectionName = req.body.source.type.toLowerCase();
    console.log(req.body.source.id)
    //直接cite
    var ifm_filter =[{_id:ObjectID(req.body.source.id)},{}];
    var str = req.body.relation +'.'+req.body.target.id//+'._nor';
    ifm_filter[1][str] = {_nor:1};
    ifm.relationAdd(sourceCollectionName,ifm_filter,function(err,doc,collectionName){
        return res.send({ifm:doc});
    })
    //获取他们的cfm信息
    var sourceCollectionName = req.body.source.type.toLowerCase();
    var source_filter = {_id:ObjectID(req.body.source.id)}
    ifm.get(sourceCollectionName,source_filter,function(err,doc,collectionName){
        var source_cfm_id = doc[0].cfm_id;

        var targetCollectionName = req.body.target.type.toLowerCase();
        var target_filter = {_id:ObjectID(req.body.target.id)}
        ifm.get(targetCollectionName,target_filter,function(err,doc,collectionName){
            var target_filter_cfm_id = (doc[0].cfm_id).toString();
            console.log(typeof source_cfm_id)
            var cfm_filter =[{_id:source_cfm_id},{}];
            var string = req.body.relation + '.' + target_filter_cfm_id + '._nor';
            cfm_filter[1][string] = 1;

            cfm.ref(sourceCollectionName,cfm_filter[0],cfm_filter[1],function(err,doc,collectionName){
                //完成
            })
        });
    });
};

ifmRelationRemove = function(req,res){
    console.log("ifmRelation remove");

    var sourceCollectionName = req.body.source.type.toLowerCase();

    //直接cite
    var ifm_filter =[{_id:ObjectID(req.body.source.id)},{}];
    var str = req.body.relation +'.'+req.body.target.id//+'._nor';
    ifm_filter[1][str] = {_nor:1};
    console.log(ifm_filter)
    ifm.relationRemove(sourceCollectionName,ifm_filter,function(err,doc,collectionName){
        return res.send({ifm:doc});
    })
    //获取他们的cfm信息

    var sourceCollectionName = req.body.source.type.toLowerCase();
    var source_filter = {_id:ObjectID(req.body.source.id)}
    ifm.get(sourceCollectionName,source_filter,function(err,doc,collectionName){
        var source_cfm_id = doc[0].cfm_id;

        var targetCollectionName = req.body.target.type.toLowerCase();
        var target_filter = {_id:ObjectID(req.body.target.id)}
        ifm.get(targetCollectionName,target_filter,function(err,doc,collectionName){
            var target_filter_cfm_id = (doc[0].cfm_id).toString();
            console.log(typeof source_cfm_id)
            var cfm_filter =[{_id:source_cfm_id},{}];
            var string = req.body.relation + '.' + target_filter_cfm_id + '._nor';
            cfm_filter[1][string] = -1;

            cfm.ref(sourceCollectionName,cfm_filter[0],cfm_filter[1],function(err,doc,collectionName){
                //完成
            })
        });
    });
}

ifmRelationRevise = function(req,res){
    console.log("ifmRelation revise");
    if(req.body.relation === 'name') return ifmReviseName(req,res);
    else{
        var sourceCollectionName = req.body.source.type.toLowerCase();
        //删除
        var ifm_filter_remove =[{_id:ObjectID(req.body.source.id)},{}];
        var str = req.body.relation +'.'+req.body.target.old.id//+'._nor';
        ifm_filter_remove[1][str] = {_nor:1};
        ifm.relationRemove(sourceCollectionName,ifm_filter_remove,function(err,doc,collectionName){
            //return res.send({ifm:doc});
            //cite
            var ifm_filter_add =[{_id:ObjectID(req.body.source.id)},{}];
            var str = req.body.relation +'.'+req.body.target.new.id//+'._nor';
            ifm_filter_add[1][str] = {_nor:1};
            ifm.relationAdd(sourceCollectionName,ifm_filter_add,function(err,doc,collectionName){
                return res.send({ifm:doc});
            })
        })

        var sourceCollectionName = req.body.source.type.toLowerCase();
        //直接cite
        var ifm_filter =[{_id:ObjectID(req.body.source.id)},{}];
        var str = req.body.relation +'.'+req.body.target.id//+'._nor';
        ifm_filter[1][str] = {_nor:1};
        console.log(ifm_filter)
        ifm.relationRemove(sourceCollectionName,ifm_filter,function(err,doc,collectionName){
            return res.send({ifm:doc});
        })
        //获取他们的cfm信息

        var sourceCollectionName = req.body.source.type.toLowerCase();
        var source_filter = {_id:ObjectID(req.body.source.id)}
        ifm.get(sourceCollectionName,source_filter,function(err,doc,collectionName){
            var source_cfm_id = doc[0].cfm_id;

            var targetCollectionName = req.body.target.old.type.toLowerCase();
            var target_filter = {_id:ObjectID(req.body.target.old.id)}
            ifm.get(targetCollectionName,target_filter,function(err,doc,collectionName){
                if(doc[0] != undefined) {
                    var target_filter_old_cfm_id = (doc[0].cfm_id).toString();
                    var string1 = req.body.relation + '.' + target_filter_old_cfm_id + '._nor';
                }


                var targetCollectionName = req.body.target.new.type.toLowerCase();
                var target_filter = {_id:ObjectID(req.body.target.new.id)}
                ifm.get(targetCollectionName,target_filter,function(err,doc,collectionName){
                    if(doc[0] != undefined){
                        var target_filter_new_cfm_id = (doc[0].cfm_id).toString();
                        var string2 = req.body.relation + '.' + target_filter_new_cfm_id + '._nor';
                    }

                    var cfm_filter =[{_id:source_cfm_id},{}];
                    if(string1 != undefined) cfm_filter[1][string1] = -1;
                    if(string2 != undefined) cfm_filter[1][string2] = 1;

                    cfm.ref(sourceCollectionName,cfm_filter[0],cfm_filter[1],function(err,doc,collectionName){
                        //完成
                    })
                });
            });
        });
    }


}

ifmReviseName = function(req,res){
    console.log("ifmRelation reviseName");
    var sourceCollectionName = req.body.source.type.toLowerCase();
    //删除
    var ifm_filter_remove =[{_id:ObjectID(req.body.source.id)},{}];
    var str = req.body.relation +'.'+req.body.old//+'._nor';
    ifm_filter_remove[1][str] = {_nor:1};
    ifm.relationRemove(sourceCollectionName,ifm_filter_remove,function(err,doc,collectionName){
        //cite
        var ifm_filter_add =[{_id:ObjectID(req.body.source.id)},{}];
        var str = req.body.relation +'.'+req.body.new//+'._nor';
        ifm_filter_add[1][str] = {_nor:1};
        ifm.relationAdd(sourceCollectionName,ifm_filter_add,function(err,doc,collectionName){
            return res.send({ifm:doc});
        })
    })

    //获取他们的cfm信息
    var sourceCollectionName = req.body.source.type.toLowerCase();
    var source_filter = {_id:ObjectID(req.body.source.id)}
    ifm.get(sourceCollectionName,source_filter,function(err,doc,collectionName){
        var source_cfm_id = doc[0].cfm_id;

        var cfm_filter =[{_id:source_cfm_id},{}];
        var string1 = req.body.relation + '.' + req.body.old + '._nor';
        cfm_filter[1][string1] = -1;
        var string2 = req.body.relation + '.' + req.body.new + '._nor';
        cfm_filter[1][string2] = 1;
        cfm.ref(sourceCollectionName,cfm_filter[0],cfm_filter[1],function(err,doc,collectionName){
            //完成
        })
    });
}

ifmRemove = function(req,res){
    console.log("Ifm remove");
    console.log(req.body);

    var collectionName = req.body.source.type.toLowerCase();
    //var filter = {cfm_id:ObjectID(req.body.source.id),user:req.session.user.mail};
    var filter = {_id:ObjectID(req.body.source.id)};

    ifm.remove(collectionName,filter,function(err,doc){
        if(doc.length != 0) removeChildNodes(collectionName,doc);
        //此处要添加对cfm的remove操作，未完成
        res.send({error:null});
    })
};

removeChildNodes = function removeChildNodes(collectionName,doc){
    for(var i=0;i<doc.length;i++){
        var filter = {};
        filter["is-a."+doc[i]._id+'._nor'] = 1;
        //filter["is-a."+doc[i].cfm_id+'._nor'] = 1;
        //filter["user"]=doc[i].user;
        ifm.remove(collectionName,filter,function(err,InnerDoc){
            console.log(InnerDoc.length);
            if(InnerDoc.length != 0) removeChildNodes(collectionName,InnerDoc);
        });
    }
}

ifmRevise = function(req,res){

};


///*
var Ifm = require('../models/ifm.js');
var Cfm = require('../models/cfm.js');
var ifmIndex = require('../models/ifmIndex.js');
var cfmIndex = require('../models/cfmIndex.js');
var operationMeasure = require('../models/operationMeasure.js');
var ObjectID = require("mongodb").ObjectID;

var generate = require('../models/generate.js');
//var logger = require('../models/logger.js').getLogger('INFO');
//ifm



ifmRevise = function(req,res){
    console.log("Ifm revise");
    var reviseType = req.body['type'];
    var info = Ifm.getInfo(req.body['type'],req.body['statusArray']);
    var filter = [{_id:info.id},{}];

    switch(reviseType){
        case '_description':
            Ifm.generateElement(req.body['type'],req.body['statusArray'],null,req.body['data']['sub'],function(id,element){
                //console.log(element);
                Ifm.copy(id,element,function(err,count){
                    Ifm.get(id,function(err,doc){
                        res.send({count:count,ifm:doc});
                    })
                });
            });
            break;

        default://fm class relation attribute
            if(req.body['data']['old'] != ""){      //根据老的添加逻辑中的多层添加，新逻辑中可能并不需要
                filter[1][info.dir+ '.'+req.body.data.old] = 1;
                console.log("filter&&&&&&&&&&&&&")
                console.log(filter);
                Ifm.delete(filter,function(err,count){
                    filter[1] = {};
                    filter[1][info.dir+ '.'+req.body.data.new+'._nor'] = 1;
                    console.log("filter&&&&&&&&&&&&&")
                    console.log(filter);
                    Ifm.add(filter,function(err,count){
                        Ifm.get(filter[0],function(err,doc){
                            res.send({count:count,ifm:doc});
                        });
                    });
                });
                Cfm.generateSubFilter(req.body['data']['sub'],function(subFilter){
                    console.log("subFilter");
                    console.log(subFilter);
                    var cfmFilter = {};
                    var preFilterOld = "";
                    var preFilterNew = "";
                    if(reviseType != 'fm'){
                        preFilterOld = info.dir+"."+req.body.data.old+".";
                        preFilterNew = info.dir+"."+req.body.data.new+".";
                    }//else preFilter = ""
                    for(var i=0;i<subFilter.length;i++){
                        cfmFilter[preFilterOld+subFilter[i]] = -1;
                        cfmFilter[preFilterNew+subFilter[i]] = 1;
                    }

                    operationMeasure.operationReveise(reviseType,ObjectID(req.body['statusArray']._id),req.body['data']['sub'],subFilter,ObjectID(req.body['statusArray'].cfm_id),cfmFilter,function(){
                        console.log("cfmRemove Filter");
                        console.log(cfmFilter);
                        //delete的操作和xxx的操作。
                        Cfm.ref( {'_id':ObjectID(req.body['statusArray']['cfm_id'])},cfmFilter,function(err,number){
                        });
                    })
                });
            }
            //完成一次引用
            //给一个copy函数？？？ 由于copy过程中，数据数据可能丢失
            // 到时候再修改吧，当前的仅能完成单层次的修改。
    }
};

ifmMultiCite = function(req,res){
    console.log("Ifm multiCite");
    //更合理的应当Check一下数据库，此处先简略操作，同时因为我前台每次点击都会更新Cfm信息，所以基本能够保持一致。
    var reviseType = req.body['type'];
    var info = Ifm.getInfo(req.body['type'],req.body['statusArray']);
    //建立查询元素
    var filter = [{_id:info.id},{}];
    console.log("info&&&&&&&&&&&&&")
    console.log(info);

    if(req.body['data']['new']['id'] === '&default'){
        req.body['data']['new']['id'] =  Cfm.generateID(req.body['type'],req.body['data']['new']['value'],info.dir);
    }
    console.log("req.body['data']['new']&&&&&&&&&&&&&")
    console.log(req.body['data']['new']);
    console.log(req.body['data']['new']['sub']['order']);
    //it really does is change json into strings
    Cfm.generateSubFilter(req.body['data']['new']['sub'],function(subFilter){
        console.log("subFilter");
        console.log(subFilter);

        var cfmFilter = {};
        var preFilter = "";
        if(reviseType != 'fm'){
            preFilter = info.dir+"."+req.body.data.new.id+".";
        }//else preFilter = ""
        for(var i=0;i<subFilter.length;i++){
            cfmFilter[preFilter+subFilter[i]] = 1;
        }
        console.log("cfmRemove Filter");
        console.log(cfmFilter);
        Ifm.add( [{'_id':info.id},cfmFilter],function(err,number){
            Ifm.get(filter[0],function(err,doc){res.send({count:number,ifm:doc});});
        });
        operationMeasure.operationMultiCite(ObjectID(req.body['statusArray']._id),subFilter,function(){
            Cfm.ref( {'_id':ObjectID(req.body['statusArray']['cfm_id'])},cfmFilter,function(err,number){
            });
        })
    });

};

ifmMultiRevise = function(req,res){
    console.log("Ifm multiRevise");
    //更合理的应当Check一下数据库，此处先简略操作，同时因为我前台每次点击都会更新Cfm信息，所以基本能够保持一致。
    var reviseType = req.body['type'];
    if(reviseType = 'relationType') req.body['statusArray']['relationType'].type = req.body['data']['old'].type;
    //
    var info = Ifm.getInfo(req.body['type'],req.body['statusArray']);
    //建立查询元素
    var filter = [{_id:info.id},{}];
    if(req.body['data']['new']['id'] === '&default'){
        req.body['data']['new']['id'] =  Cfm.generateID(req.body['type'],req.body['data']['new']['value'],info.dir);
    }
    console.log("info&&&&&&&&&&&&&")
    console.log(info);

    console.log("req.body['data']['old']&&&&&&&&&&&&&")
    console.log(req.body['data']['old']);

    console.log("req.body['data']['new']&&&&&&&&&&&&&")
    console.log(req.body['data']['new']);
    //it really does is change json into strings

    filter[1][info.dir+ '.'+req.body.data.old.id] = -1;
    console.log("filter&&&&&&&&&&&&&")
    console.log(filter);
    Ifm.delete(filter,function(err,count){
        //引用一定要在内部，因为可能两者是一样的。。
        if(reviseType = 'relationType') req.body['statusArray']['relationType'].type = req.body['data']['new'].type;
        var info = Ifm.getInfo(req.body['type'],req.body['statusArray']);
        Cfm.generateSubFilter(req.body['data']['new']['sub'],function(subFilter){
            console.log("subFilter");
            console.log(subFilter);
            var cfmFilter = {};
            var preFilter = "";
            if(reviseType != 'fm'){
                preFilter = info.dir+"."+req.body.data.new.id+".";
            }//else preFilter = ""
            for(var i=0;i<subFilter.length;i++){
                cfmFilter[preFilter+subFilter[i]] = 1;
            }
            console.log("cfmRemove Filter");
            console.log(cfmFilter);
            Ifm.add( [{'_id':info.id},cfmFilter],function(err,number){
                Ifm.get(filter[0],function(err,doc){res.send({count:number,ifm:doc});});
            });
            operationMeasure.operationMultiCite(ObjectID(req.body['statusArray']._id),subFilter,function(){
                Cfm.ref( {'_id':ObjectID(req.body['statusArray']['cfm_id'])},cfmFilter,function(err,number){
                });
            })
        });
    });

    //去引用
    Cfm.generateSubFilter(req.body['data']['old']['sub'],function(subFilter){
        console.log("subFilter");
        console.log(subFilter);
        var cfmFilter = {};
        var preFilter = "";
        if(reviseType != 'fm'){
            preFilter = info.dir+"."+req.body.data.old.id+".";
        }//else preFilter = ""
        for(var i=0;i<subFilter.length;i++){
            cfmFilter[preFilter+subFilter[i]] = -1;
        }
        console.log("cfmRemove Filter");
        console.log(cfmFilter);
        operationMeasure.operationReveise(reviseType,ObjectID(req.body['statusArray']._id),req.body['data']['old']['sub'],subFilter,ObjectID(req.body['statusArray'].cfm_id),cfmFilter,function(){
            Cfm.ref( {'_id':ObjectID(req.body['statusArray']['cfm_id'])},cfmFilter,function(err,number){
            });
        });
    });
};

//cfm
exports.cfm = function(req, res) {
    console.log("dataCfm");
    Cfm.get({_id:ObjectID(req.body['id'])},function(err,doc){
        res.send({cfm:doc});
    });
};

exports.index = function(req,res){
    console.log("dataIndex");
    var filter = {};
    var ifm_index=[];
    var cfm_index;
    filter["user"] = req.body.user;

    ifmIndex.get(filter,function(err,doc){
        var exist = [];
        for(var key in doc[0]){
            if(key != 'user' && key != '_id'){
                console.log("push key");
                exist.push(ObjectID(key));
                ifm_index.push(doc[0][ObjectID(key)]);
            }
        }

        console.log(exist);
        var filter = {};
        filter["_id"] ={};
        filter["_id"]["$nin"] = exist;

        cfmIndex.get(filter,function(err,doc){
            cfm_index = doc;
            console.log("*************");
            console.log(ifm_index);
            console.log("*************");
            console.log(cfm_index);
            //console.log(ifm_index[0].last_time.toDateString());
            res.send({ifm_index:ifm_index,cfm_index:cfm_index});
        });
    });
};

exports.intro = function(req,res){
    console.log("dataIndex");
    var filter = {};
    var ifm_index=[];
    var cfm_index;
    filter["user"] = req.body.user;

    ifmIndex.get(filter,function(err,doc){
        var exist = [];
        //console.log(req.body.cfm_id)

        var key = ObjectID(req.body.cfm_id)

        exist.push(key);
        ifm_index.push(doc[0][key]);

        var filter = {};
        filter["_id"] ={};
        filter["_id"]["$in"] = exist;

        cfmIndex.get(filter,function(err,doc){
            cfm_index = doc;
            res.send({ifm_index:ifm_index,cfm_index:cfm_index});
        });
    });
};

exports.ifmOperationValue = function(req, res) {
    operationMeasure.getOperationValue(ObjectID(req.body['statusArray']._id),ObjectID(req.body['statusArray'].cfm_id),function(doc){
        console.log(doc);
        res.send(doc);
    })
}
//*/